package com.mianli.meepo

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import javax.websocket.*
import javax.websocket.server.ServerEndpoint
import java.util.concurrent.CopyOnWriteArraySet
import java.io.IOException
import javax.swing.text.html.parser.Parser
import kotlin.math.log

/**
 * 用于同步数据信息的kotlin类
 */
@Component
@ServerEndpoint(value = "/websocket")
class WebSocketServer {

    var LEVEL = 0;
    var NAME = "PSA";

    companion object {
        var logger : Logger = LoggerFactory.getLogger(WebSocketServer::class.java)
        var psaEntity: PSADataEntity = PSADataEntity();
        var psaCommand: PSACommand = PSACommand();
        private var webSocketSet = CopyOnWriteArraySet<WebSocketServer>()
    }

    var session: Session? = null

    @OnOpen
    fun onOpen(session: Session) {
        logger.info("OnOpen")
        this.session = session
        //建立一个当前session id的状态数据连接
        webSocketSet.add(this);
        sendMessage("{\"msg\":\"连接成功\"}")
    }

    @OnClose
    fun onClose() {
        logger.info("onClose")
        webSocketSet.remove(this);
    }

    /**
     * 接受到客户端发送的消息
     */
    @OnMessage
    fun onMessage(message: String, session: Session) {
        logger.info("-------")
        logger.info("接受消息");
        logger.info(message);
        logger.info("-------")
        if(message.contains("CONTROL")){
            //转换成JSON消息
            logger.info("CONTROL端消息")
            logger.info("-------")
            //转发
            sendInfo(message);
        }else if(message.contains("CENTRAL")){
            //忽略其他消息
            if(message.contains("NAME")){
                sendInfo("{\"msg\":\"" + NAME + "\", \"level\":"+ LEVEL + "}")
            }
        }
    }

    @OnError
    fun onError(session: Session, throwable: Throwable) {
        logger.info("onError")
    }

    private fun sendMessage(message: String) {
        this.session!!.basicRemote.sendText(message)
    }

    private fun sendInfo(info: String){
        logger.info("-------")
        logger.info("发送消息");
        logger.info(info);
        logger.info("-------")
        for (item in webSocketSet) {
            try {
                item.sendMessage(info)
            } catch (e: IOException) {
                continue
            }

        }
    }
}